import ForgeStart from "@/assets/audio/forge_start.mp3";
import LoseAudio from "@/assets/audio/lose.mp3";
import TickAudio from "@/assets/audio/tick.mp3";
import BasicWin from "@/assets/audio/win.mp3";

window.AudioContext = window.AudioContext || window.webkitAudioContext;

export class AudioUtils {
  audioContext: any = null;
  buffers: any = {};

  constructor() {
    this.initAudioContext();
  }

  async initAudioContext() {
    if (!this.audioContext) {
      this.audioContext = new window.AudioContext({
        latencyHint: "interactive",
        sampleRate: 44100,
      });

      if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
        const handleFirstTouch = () => {
          if (this.audioContext && this.audioContext.state === "suspended") {
            this.audioContext.resume();
          }
          window.removeEventListener("touchstart", handleFirstTouch);
        };
        window.addEventListener("touchstart", handleFirstTouch);
      }

      await this.loadAudioAssets();
    }
  }

  async loadAudioAssets() {
    await Promise.all([
      this.loadAudio("lose", LoseAudio),
      this.loadAudio("win", BasicWin),
      this.loadAudio("tick", TickAudio),
      this.loadAudio("forge", ForgeStart),
    ]);
  }

  async loadAudio(key, url) {
    if (this.buffers[url]) {
      return;
    }
    const response = await fetch(url);
    const arrayBuffer = await response.arrayBuffer();
    const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
    this.buffers[key] = audioBuffer;
  }

  playAudio(buffer) {
    const source = this.audioContext.createBufferSource();
    source.buffer = buffer;

    const gainNode = this.audioContext.createGain();
    source.connect(gainNode);
    gainNode.connect(this.audioContext.destination);
    source.start(this.audioContext.currentTime);
  }

  ticksPlay() {
    try {
      this.playAudio(this.buffers["tick"]);
    } catch (error) {
      alert("111");
    }
  }

  losePlay() {
    this.playAudio(this.buffers["lose"]);
  }

  winPlay() {
    this.playAudio(this.buffers["win"]);
  }

  forgeStartPlay() {
    this.playAudio(this.buffers["forge"]);
  }
}
